package controler;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.util.Observable;

import javax.swing.text.JTextComponent;

import model.TextModel;

import template.AbstractListener;
import template.AbstractSystem;

import utils.Dom;
import utils.User;

import org.jdom.Element;

public class LoginListener extends AbstractListener implements ActionListener {

	private static final long serialVersionUID = 1L;
	private JTextComponent usernameField;
	private JTextComponent passwordField;
	private Element XMLFileRoot;

	public LoginListener(Observable obs, JTextComponent uf, JTextComponent pf) {
		addModel(obs);

		usernameField = uf;
		passwordField = pf;

		XMLFileRoot = Dom.getXMLFile("users.xml").getRootElement();
	}

	public void actionPerformed(ActionEvent evt) {
		TextModel model = (TextModel) getModel(0);

		if (isEntriesValid()) {
			new User(usernameField.getText(), passwordField.getText());
			AbstractSystem.setSystemType(XMLFileRoot.getChild(
					usernameField.getText()).getAttributeValue("type"));
			AbstractSystem.CURRENTSYSTEM.dispose();
		} else {
			model.setText("CANNOT LOGIN WITH THESE ENTRIES !");
		}
	}

	private Boolean isEntriesValid() {
		return (isUsernameValid()) ? isPasswordValid() : false;
	}

	private Boolean isUsernameValid() {
		return (XMLFileRoot.getChild(usernameField.getText()) != null) ? true
				: false;
	}

	private Boolean isPasswordValid() {
		return (XMLFileRoot.getChild(usernameField.getText()).getChildText(
				"password").equals(passwordField.getText())) ? true : false;
	}

}
